package com.yuan.blog.controller;


import com.yuan.blog.entity.UserEntity;
import com.yuan.blog.service.IUserService;
import com.yuan.blog.service.impl.UserServiceImpl;
import com.yuan.blog.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@Controller
@RequestMapping("/FileController")
//@PropertySource(value = {"myconfig.properties"})
@Slf4j
public class FileController{

    @Value("${blog.uploadPath}")
    private String uploadPath;

    @Value("${blog.defaultPng}")
    private String defaultPng;


    @PostMapping("/upload")
    @ResponseBody
    public R upload(@RequestParam("pngFile") MultipartFile file, HttpServletRequest req) throws Exception {

        log.info("上传路径: " + uploadPath);
        log.info("defaultPng: " + defaultPng);
        // 4.文件的路径
        String filePath = uploadPath + "/" + file.getOriginalFilename();

        FileOutputStream ops = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ops = new FileOutputStream(filePath);
            IOUtils.copy(inputStream, ops);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(ops);
        }
        return R.ok(filePath);
    }

    @GetMapping("/showPng")
//    @ResponseBody
    public void showPng(String filePath,HttpServletResponse resp) throws Exception {
        FileInputStream ips = null;
        try {
            try {
                ips = new FileInputStream(filePath);//从本地找图片
            } catch (FileNotFoundException e) {
                ips = new FileInputStream(defaultPng); // 扎到读取默认的
            }finally {
                // IO流拷贝，把ips中的内容拷贝ops中
                IOUtils.copy(ips, resp.getOutputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ips);
        }
    }
}
